var express = require('express')
  , app = express()
  , site = require('./site')
  , post = require('./post')
  , user = require('./user')
  , util = require('./util');

var crypto = require('crypto')
	, MongoStore = require('connect-mongo')(express)
	, settings = require('./settings.js');

app.use(express.compress());
app.use(express.favicon(__dirname + '/public/favicon.ico'));
app.set('view engine', 'html');
app.engine('html', require('ejs').renderFile);
//app.set('view engine', 'jade');
app.set('views', __dirname + '/views');
app.use(express.logger('dev'));
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(__dirname + '/public'));
//app.use(express.session({secret: '1234567890QWERTY'}));
app.use(express.session({ 
	  secret: settings.cookieSecret, 
	  store: new MongoStore({ 
	  db: settings.db 
   }) 
}));



//Param
app.param(function(name, fn){
  if (fn instanceof RegExp) {
	return function(req, res, next, val){
	  var captures;
	  if (captures = fn.exec(String(val))) {
		req.params[name] = captures;
		next();
	  } else {
		next('route');
	  }
	}
  }
});
app.param('num', /^\d+$/);
app.param('str', /^\w+$/);
// General

app.get('/', site.index);
app.get('/about', site.about);
app.get('/contact',site.contact);
app.get('/services',site.services);
app.get('/pricing',site.pricing);
app.get('/shortcodes',site.shortcodes);

//Portfolio
app.get('/portfolio/:num', function(req, res, next){
  res.render('portfolio' + req.params.num, req.query);
  next();
});
app.get('/portfolio/:str', function(req, res, next){
	console.log("----------");
  res.render('portfolio-' + req.params.str, req.query);
  next();
});
app.get('/portfolio/:num/:str', function(req, res, next){
  res.render('portfolio' + req.params.num + "-" +req.params.str, req.query);
  next();
});

//Blog
app.get('/blog', function(req, res, next){
  res.render('blog', req.query);
  next();
});
app.get('/blog/:str', function(req, res, next){
  res.render('blog-' + req.params.str, req.query);
});
//User auth
app.get('/auth', function(req, res, next){
  res.render('auth', {'box' : 'login'});
  next();
});
app.get('/login', function(req, res){
	 res.render('auth', {'box' : 'login'});
});
app.get('/forgot', function(req, res){
	 res.render('auth', {'box' : 'forgot'});
});
app.get('/register', function(req, res){
	 res.render('auth', {'box' : 'register'});
});
app.get('/auth/:str', function(req, res, next){
  res.render('auth', {'box' : req.params.str});
});

app.post('/login', function(req, res) {
	console.log(req.query.uid);
	//res.send(JSON.stringify(req.body));
	var md5 = crypto.createHash('md5'),
	password = md5.update(req.body.password).digest('base64');
	User.get(req.body.username, function(err, user){
		if(!user){
			req.flash('error', '用户不存在'); 
			return res.redirect('/login'); 
		}
		if(user.password != password){
			req.flash('error', '密码错误'); 
			return res.redirect('/login');
		}
		req.session.user = user;
		req.flash('success','登陆成功');
		res.redirect('/');
	});
});
app.get('/logout', function(req, res){
	req.session.user = null;
	req.flash('success','登出成功');
	res.redirect('/');
});
app.post('/register', function(req, res) {
	console.log(req.query.uid);
	//res.send(JSON.stringify(req.body));
	
	var md5 = crypto.createHash('md5');
	var password = md5.update(req.body.password).digest('base64');
	var newUser = new User({
		name: req.body.username,
		password: password,
	});
	User.get(newUser.name, function(err, user){
		if(user){
			err = '用户已存在';
		}
		if(err){
			req.flash('error', err);
			return res.redirect('/register');
		}
		newUser.save(function(err){
			if(err){
				req.flash('error',err);
				return res.redirect('/register');
			}
			req.session.user = newUser;
			req.flash('success','注册成功');
			res.redirect('/');
		});
	});
});
app.post('/forgot', function(req, res) {
	console.log(req.query.uid);
	res.send(JSON.stringify(req.body));
});
// User
app.all('/users', user.list);
app.all('/user/:id/:op?', user.load);
app.get('/user/:id', user.view);
app.get('/user/:id/view', user.view);
app.get('/user/:id/edit', user.edit);
app.put('/user/:id/edit', user.update);

// Posts

app.get('/posts', post.list);

//errors
app.use(function(err, req, res, next){
  // treat as 404
  if (~err.message.indexOf('not found')) return next();
  // log it
  console.error(err.stack);
  // error page
  res.status(500).render('errors/5xx');
});
// assume 404 since no middleware responded
app.use(function(req, res, next){
  res.status(404).render('errors/404', { url: req.originalUrl });
});